/**
 * 本地存储工具函数
 */

/**
 * 存储数据到localStorage
 * @param key 键
 * @param value 值
 */
export const setLocalStorage = (key: string, value: any): void => {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    console.error('Error saving to localStorage', error);
  }
};

/**
 * 从localStorage获取数据
 * @param key 键
 * @param defaultValue 默认值
 * @returns 值
 */
export const getLocalStorage = <T>(key: string, defaultValue?: T): T | undefined => {
  try {
    const value = localStorage.getItem(key);
    if (value === null) {
      return defaultValue;
    }
    return JSON.parse(value) as T;
  } catch (error) {
    console.error('Error reading from localStorage', error);
    return defaultValue;
  }
};

/**
 * 从localStorage删除数据
 * @param key 键
 */
export const removeLocalStorage = (key: string): void => {
  try {
    localStorage.removeItem(key);
  } catch (error) {
    console.error('Error removing from localStorage', error);
  }
};

/**
 * 清空localStorage
 */
export const clearLocalStorage = (): void => {
  try {
    localStorage.clear();
  } catch (error) {
    console.error('Error clearing localStorage', error);
  }
}; 